<template>
	<view class="bi-car-number-keyboard">
		<view class="bi-car-number-keyboard__handle" @click="handleToggleClick">
			<slot></slot>
		</view>
		<ui-popup 
			class="bi-car-number-keyboard__main"
			v-model="visible"
			@input="handlePopupVisibleChange"
		>
			<view class="bi-car-number-keyboard__inner">
				<ui-keyboard
					@item-click="handleKeyboardItemClick"
				>
					<view class="bi-car-number-keyboard__value" slot="addon">
						<view 
							class="bi-car-number-keyboard__value-item"
							v-for="(item, index) in number"
							:key="index"
							:class="{'is-active': innerActiveIndex === index}"
							@click="handleNumberItemClick(item, index)"
						>{{item || '-'}}</view>
					</view>
				</ui-keyboard>
			</view>
		</ui-popup>
	</view>
</template>

<script>
	export default {
		props: {
			value: {
				type: String
			},
			activeIndex: {
				type: Number
			}
		},
		data () {
			return {
				visible: false,
				innerValue: this.value,
				innerActiveIndex: this.activeIndex
			}
		},
		watch: {
			value () {
				this.innerValue = this.value || ''
			},
			activeIndex () {
				this.innerActiveIndex = this.activeIndex
			}
		},
		computed: {
			number () {
				const vs = this.innerValue ? this.innerValue.split('') : []
				const nt = []
				for (let i = 0; i < 6; i++) {
					nt.push(vs[i] ? vs[i] : '')
				}
				return nt
			}
		},
		methods: {
			handleToggleClick () {
				this.open()
			},
			handleKeyboardItemClick ({ item }) {
				let index = this.innerActiveIndex
				if (item.type === 'value') {
					const nextNumber = [...this.number]
					if (index < 0) {
						nextNumber[0] = item.value
						index = 0
					} else {
						if (index >= 6) {
							index = 5
						}
						nextNumber[index] = item.value
					}
					this.innerValue = nextNumber.join('')
					this.innerActiveIndex = Math.min(index + 1, 5)
				} else if (item.type === 'confirm') {
					this.visible = false
					this.$emit('input', this.innerValue)
				}
			},
			handleNumberItemClick (item, index) {
				this.innerActiveIndex = index
			},
			handlePopupVisibleChange (visible) {
				if (!visible) {
					this.innerValue = this.value
				}
			},
			open () {
				this.visible = true
			},
			close () {
				this.visible = false
			}
		}
	}
</script>

<style lang="scss">
	.bi-car-number-keyboard__value{
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		min-height: 24px;
		line-height: 24px;
		padding: 3px;
	}
	.bi-car-number-keyboard__value-item{
		padding: 0 3px;
		border: 1px solid #eee;
		border-radius: 3px;
		height: 24px;
		min-width: 20px;
		text-align: center;
		line-height: 24px;
		margin: 0 2px;
		&.is-active{
			color: #fff;
			background-color: #423f52;
			border-color: #423f52;
		}
	}
	.bi-car-number-keyboard__inner{
		background-color: #f6f6f6;
		padding-bottom: calc(constant(safe-area-inset-bottom));
		padding-bottom: calc(env(safe-area-inset-bottom));  
	}
</style>
